package cn.xspace.wnx.fragment;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.FileUtil;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PageUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.SelectDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.filemg.activity.FileActivity;
import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.view.TitleBar;
import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.EmojiconEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.chatui.view.chat.ChatExtendMenu;
import cn.xspace.chatui.view.chat.ChatInputMenu;
import cn.xspace.chatui.view.chat.VoiceRecorderView;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.ContentType;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatActivity;
import cn.xspace.wnx.activity.ChatInfoActivity;
import cn.xspace.wnx.activity.ImageLargerActivity;
import cn.xspace.wnx.activity.MapLocationGetActivity;
import cn.xspace.wnx.activity.MsgForwardActivity;
import cn.xspace.wnx.activity.VideoCallActivity;
import cn.xspace.wnx.db.ChatRecordDao;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.entity.GroupEntity;
import cn.xspace.wnx.util.Navigator;
import cn.xspace.wnx.view.chat.ChatMessageList;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/13.
 */

public class ChatFragment extends BaseFragment {
    public static final String PAGE_TYPE = "pageType";
    public static final String TAG = ChatFragment.class.getSimpleName();
    protected ChatMessageList messageList;
    protected TitleBar mTitleBar;
    protected ChatInputMenu inputMenu;
    private LinearLayout mLinear_form;
    private TextView mTextview_name;
    private TextView mTextview_time;

    protected SwipeRefreshLayout swipeRefreshLayout;
    private LocalBroadcastManager broadcastManager;
    protected ListView listView;
    protected VoiceRecorderView voiceRecorderView;
    private ArrayList<MsgRecordEntity> mDataList;
    private MessageEntity messageEntity;
    private int chatType = MsgType.CHAT_SINGLE.toNumber();
    private String id = ""; //群组时group_id 单聊是sender_id
    private String name = "";
    private String sex = "";
    private String logo = "";
    private String userId = "";
    private boolean isJustRecord = false;
    private String otherId = "";
    private int mContentType = ContentType.TXT.toNumber();
    private String mContent = "";
    IntentFilter intentFilter;
    //    BroadcastReceiver mReceiver;
    static final int ITEM_PICTURE = 1;
    static final int ITEM_TAKE_PICTURE = 2;
    static final int ITEM_LOCATION = 3;
    static final int ITEM_FILE = 4;
    static final int ITEM_VIDEO_CALL = 5;
    protected File cameraFile;
    private MessageEntity sendMsg;
    private MsgRecordEntity sendMsgRecord;
    private Map<String, Object> sendMap;
    int i = 0;
    protected int[] itemdrawables = {R.drawable.selector_attach_picture, R.drawable.selector_attach_take_pic,
            R.drawable.selector_attach_location, R.drawable.selector_attach_file};
    protected int[] itemIds = {ITEM_PICTURE, ITEM_TAKE_PICTURE, ITEM_LOCATION, ITEM_FILE};
    protected MyItemClickListener extendMenuItemClickListener;
    private int voiceTime = 0;
    protected boolean haveMoreDataLocal = true;
    protected boolean haveMoreDataRemote = true;
    protected boolean isloading;
    private Map<String, Object> dataMap;
    private double lat = 0.0;
    private double lng = 0.0;
    private String locaPath = "";
    private String address = "";
    private GroupEntity mGroupEntity = null;
    private String groupNameSplit = null;
    private int groupMember = 0;
    private int mGroupType = Type.GroupType.TEMP_GROUP;
    private int isQuit = 0; //是否退出群组

    private String formId = "";
    private String formUrl = "";
    private String formName = "";
    private String formTime = "";
    private int formType = 1;
    private boolean formIsCanTalk = false;

    public static BaseFragment getInstance(Bundle args) {
        LogUtil.d(TAG, "wubaojie>>>getInstance: arg:" + args.toString());
        BaseFragment fragment = new ChatFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        if (fragmentArgs != null) { //fragmentArgs为getInstance的时候传递的参数即为arg
            isJustRecord = fragmentArgs.getBoolean(PAGE_TYPE, false);
            chatType = fragmentArgs.getInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_SINGLE.toNumber());
            mGroupType = fragmentArgs.getInt(BldNavigation.GROUP_TYPE, Type.GroupType.TEMP_GROUP);
            id = (String) fragmentArgs.get(BldNavigation.SENDER_ID);
            name = (String) fragmentArgs.get(BldNavigation.CHAT_NAME);
            logo = (String) fragmentArgs.get(BldNavigation.CHAT_SENDER_LOGO);
            sex = (String) fragmentArgs.get(BldNavigation.CHAT_SENDER_SEX);

            formId = fragmentArgs.getString(BldNavigation.FormId);
            formType = fragmentArgs.getInt(BldNavigation.FormType);
            formName = fragmentArgs.getString(BldNavigation.FormName);
            formUrl = fragmentArgs.getString(BldNavigation.FormUrl);
            formIsCanTalk = fragmentArgs.getBoolean(BldNavigation.FormCanTAlk, false);
        }

    }

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_chat, null, false);
    }

    @Override
    protected void initFindViewById(View view) {
        mTitleBar = (TitleBar) view.findViewById(R.id.title_bar);
        messageList = (ChatMessageList) view.findViewById(R.id.message_list);
        inputMenu = (ChatInputMenu) view.findViewById(R.id.input_menu);
        mLinear_form = (LinearLayout) view.findViewById(R.id.linear_form);
        mTextview_name = (TextView) view.findViewById(R.id.textview_name);
        mTextview_time = (TextView) view.findViewById(R.id.textview_time);
        if (isJustRecord) {
            inputMenu.setVisibility(View.GONE);
        } else {
            extendMenuItemClickListener = new MyItemClickListener();
            registerExtendMenuItem();
            voiceRecorderView = (VoiceRecorderView) view.findViewById(R.id.voice_recorder);
        }
        listView = messageList.getListView();
        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mDataList = new ArrayList<>();
        messageList.init("", 1, mDataList);

        if (chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
            mLinear_form.setVisibility(View.VISIBLE);
            if (formIsCanTalk) {
                inputMenu.setVisibility(View.VISIBLE);
            } else {
                inputMenu.setVisibility(View.GONE);
            }
            mTextview_name.setText(formName);
        } else {
            mLinear_form.setVisibility(View.GONE);
        }
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        inputMenu.init(null);
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    LogUtil.e(TAG, "wubaojie>>>" + "onClick: " + "finish");
                    hideSoftKeyboard();
                    inputMenu.hideExtendMenuContainer();
                    getActivity().finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
//        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Navigator.startChatMessageActivity(mContext, chatType, id, mGroupType);
//            }
//        });
        mLinear_form.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BldNavigation.viewApplyFormDetail(mContext, formUrl);
            }
        });
        inputMenu.setChatInputMenuListener(new ChatInputMenu.ChatInputMenuListener() {
                                               @Override
                                               public void onSendMessage(final String content) {
                                                   LogUtil.d(TAG, "wubaojie>>>onSendMessage: content:" + content);
                                                   mContent = content;
                                                   mContentType = ContentType.TXT.toNumber();
                                                   buildMessageListBean();
                                                   buildMessageRecordBean();
                                                   updateUIBeforeSend();
                                               }

                                               @Override
                                               public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                                                   return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new
                                                           VoiceRecorderView.EaseVoiceRecorderCallback() {

                                                               @Override
                                                               public void onVoiceRecordComplete(String voiceFilePath, int
                                                                       voiceTimeLength) {
                                                                   voiceTime = voiceTimeLength;
//                                  sendVoiceMessage(voiceFilePath, voiceTimeLength);
                                                                   LogUtil.d(TAG, "onVoiceRecordComplete   path " +
                                                                           voiceFilePath);
                                                                   String name = FileUtil.getImageNameByPath
                                                                           (voiceFilePath);
                                                                   LogUtil.d(TAG, "onVoiceRecordComplete  name " +
                                                                           name);
                                                                   sendBase64Msg(voiceFilePath, ContentType
                                                                           .VOICE.toNumber());
                                                               }
                                                           });
                                               }

                                               @Override
                                               public void onBigExpressionClicked(EmojiconEntity emojicon) {
                                                   LogUtil.d(TAG, "onBigExpressionClicked");
//                  sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
                                               }
                                           }
        );
        LogUtil.d(TAG, "设置监听");
        messageList.setItemClickListener(new ChatMessageList.MessageListItemClickListener() {
            @Override
            public void onResendClick(MsgRecordEntity message) {
                LogUtil.d(TAG, "onResendClick");
//                buildSendMsgMap();
                message.msg_send_status = MessageEntity.MsgSendStatus.NOT_SEND.toNumber();
                messageList.refresh();
            }

            @Override
            public boolean onBubbleClick(final MsgRecordEntity message) {
                LogUtil.d(TAG, "onBubbleClick" + message.msg_content_type);
                if (message.msg_content_type == ContentType.PICTURE.toNumber()) {
                    int index = mDataList.indexOf(message);
                    LogUtil.d(TAG, "wubaojie>>>onBubbleClick: " + index);
                    final ArrayList<MsgRecordEntity> imageEntityList = new ArrayList<>();
                    for (MsgRecordEntity entity : mDataList) {
                        if (entity.msg_content_type == ContentType.PICTURE.toNumber()) {
                            imageEntityList.add(entity);
                        }
                    }
                    Bundle mBundle = new Bundle();
                    mBundle.putInt(ImageLargerActivity.IMAGE_INDEX, index);
                    mBundle.putSerializable(ImageLargerActivity.IMAGE_LIST, imageEntityList);
                    Navigator.showImageLarerActivity(mContext, mBundle);
                    return true;
                } else if (message.msg_content_type == ContentType.OTHER.toNumber()) {
                    String content = message.msg_content;
                    String[] arg = content.split(Constants.CHAR_SPECIAL);
                    if (arg.length == 2) {
//                        String title = arg[0];
                        String url = arg[1];

                        Navigator.startWnxWebView(mContext, url, "", "", MsgType.WNX_MSG.toNumber());
                    }
                    return true;
                } else if (message.msg_content_type == ContentType.LOCATION.toNumber()) {
                    Intent mIntent = new Intent(mContext, MapLocationGetActivity.class); //展示地图
                    mIntent.putExtra(IntentConstant.IS_SHOW_MAP, true);
                    mIntent.putExtra(IntentConstant.LATITUDE, Double.parseDouble(message.mFileEntity.lat));
                    mIntent.putExtra(IntentConstant.LONGITUDE, Double.parseDouble(message.mFileEntity.lng));
                    mIntent.putExtra(IntentConstant.ADDRESS, message.mFileEntity.address_desc);
                    startActivity(mIntent);
                    return true;
                }
                return false;
            }

            @Override
            public void onBubbleLongClick(MsgRecordEntity message) {
                LogUtil.d(TAG, "onBubbleLongClick");
                bubbleLongClick(message);
            }

            @Override
            public void onUserAvatarClick(String userId) {
                LogUtil.d(TAG, "onUserAvatarClick");
                Navigator.startPersonCardActivity(mContext, userId);
            }

            @Override
            public void onUserAvatarLongClick(MsgRecordEntity username) {

            }
        });

        setSwipeRefreshListener();
        if (isJustRecord) {
            mTitleBar.setRightLayoutImageVisibility(View.GONE);
        } else {
            if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
                mTitleBar.setRightImageResource(R.drawable.icon_logo_user);
            } else if (chatType == MsgType.CHAT_CROUP.toNumber()) {
                mTitleBar.setRightImageResource(R.drawable.icon_logo_group);
            } else if (chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
                mTitleBar.setRightLayoutVisibility(View.GONE);
            }
            mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Navigator.startChatMessageActivity(mContext, chatType, id, mGroupType, isQuit);
                }
            });
        }
        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });
    }

    @Override
    public void initData() {
        userId = MyInfoUtil.getMyUserid(mContext);
        dataMap = new HashMap<>();
        otherId = id;
        dataMap.put("user_id", userId);
        if (isSingleChat()) {
            dataMap.put("friend_id", otherId);
            mTitleBar.setTitle(isJustRecord ?
                    getResources().getString(R.string.txt_look_chat_record) :
                    (TextUtils.isEmpty(name) ?
                            getResources().getString(R.string.ui_chat) :
                            name));
        } else {
            if (isJustRecord) {
                mTitleBar.setTitle(getResources().getString(R.string.txt_look_chat_record));
            }
            dataMap.put(RequestConstant.KEY_GROUP_ID, otherId);
            if (!isJustRecord)
                getGroupInfo();
        }
        LogUtil.d(TAG, " 初始化list 数据");
        if (isJustRecord) {
            //获取服务器记录
            haveMoreDataLocal = false;
            requestNetWork();
        } else {
            haveMoreDataRemote = false;
            registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                    .getChatRecordList(id, chatType, PAGE_INDEX, formId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<MsgRecordEntity>>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
//            swipeRefreshLayout.setRefreshing(false);
//        Toast.makeText(getActivity(), R.string.loading_failed, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onNext(List<MsgRecordEntity> dataList) {
                            Log.d(TAG, " onNext size " + dataList.size());
                            mDataList.addAll(0, dataList);

                            if (dataList.size() < PageUtil.PAGE_SIZE) {
                                haveMoreDataLocal = false;
                            }
                            messageList.refreshSelectLast();

                        }
                    }));

            if (chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
                //表单相关
                Map<String, Object> formDetail = new HashMap<>();
                formDetail.put(RequestConstant.KEY_USER_ID, id);
                formDetail.put("form_type", formType + "");
                formDetail.put("form_id", formId);
                OkHttpManager.getInstance().commonRequest(Constants.QUERY_FORM_BASEINFO, formDetail)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BaseReturnBean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BaseReturnBean baseReturnBean) {
                                try {
                                    JSONObject jsonData = new JSONObject(baseReturnBean.data);
                                    mTextview_time.setText(DateUtils.getQacQuestionList(jsonData.optString
                                            ("form_lastupdatetime"), null));
                                    int status = jsonData.optInt("form_dealstatus");
                                    if (status == 1 && "1".equals(MyInfoUtil.getIsFarmer())) {
                                        formIsCanTalk = true;
                                        inputMenu.setVisibility(View.VISIBLE);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
            }
        }
        //获取成员数量
        LogUtil.d(TAG, "mDatalistSize " + mDataList.size());
        LogUtil.d(TAG, "H获取数据");
//        MessageRecordDao.getInstance().getiMessageData().updateUnreadStatus(otherId, chatType)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(commonAction);
    }

    /**
     * 构建消息列表相关的Bean
     */
    private void buildMessageListBean() {
        sendMsg = new MessageEntity();
        sendMsg.isRead = true;
        sendMsg.msg_content_type = mContentType;
        sendMsg.msg_type = chatType;
        sendMsg.msg_send_status = MessageEntity.MsgSendStatus.NOT_SEND.toNumber();
        if (chatType == MsgType.CHAT_CROUP.toNumber()) {
            sendMsg.msg_group_id = otherId;
            sendMsg.msg_group_name = TextUtils.isEmpty(name) ? groupNameSplit : name;
            sendMsg.group_member = mGroupEntity.group_members;
            sendMsg.group_type = mGroupType;
        } else if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
            sendMsg.msg_sender_id = otherId;
        } else if (chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
            sendMsg.msg_sender_id = otherId;
        }

        sendMsg.msg_last_time = DateUtils.getNowDateTime();
        sendMsg.msg_content = ChatFileEntity.getContentByType(mContent, mContentType);
        sendMsg.msg_sender_name = name;
        sendMsg.msg_logo = logo;
    }

    /**
     * 构建消息记录相关的bean
     */
    private void buildMessageRecordBean() {
        sendMsgRecord = new MsgRecordEntity();
        sendMsgRecord.msg_logo = logo;
        sendMsgRecord.message2Record(sendMsg);
        sendMsgRecord.inserttime = System.currentTimeMillis() + "";
        sendMsgRecord.is_mine = "1";
        sendMsgRecord.user_sex = sex;

        sendMsgRecord.form_id = formId;
        sendMsgRecord.form_type = formType;
        sendMsgRecord.form_url = formUrl;
    }

    /**
     * 发送信息之前更新UI
     */
    private void updateUIBeforeSend() {
        mDataList.add(sendMsgRecord);
        LogUtil.d(TAG, "mDataList size  " + mDataList.size());
        messageList.refreshSelectLast();
        //更新消息列表o
        LogUtil.d(TAG, "wubaojie>>>updateUIBeforeSend: sendMsg:" + sendMsg.toString());

        if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
            registerSubscription(MessageRecordDao.getInstance().getiMessageData().updateMessageList(sendMsg)
                    .observeOn(Schedulers.io())
                    .subscribe());
        }
        //插入消息记录
//        ChatRecordDao.getInstance().insertMsgRecord(sendMsgRecord);
        registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation().insertMsgRecord(sendMsgRecord)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(TAG, "聊天记录插入成功" + s);
                    }
                }));

//        broadcastManager.sendBroadcast(new Intent(MessageFragment.TAG));
    }

    /**
     * 发送网络请求,并根据结果更新UI
     */

  /*  private void sendMsgCallback() {
        OkHttpManager.postAsync(Constants.sendHXSingleChatMsg, sendMap, new OkHttpManager.DataCallBack() {
            @Override
            public void requestBefore() {
                updateUIBeforeSend();
            }

            @Override
            public void requestFailure(Request request, IOException e) {
                LogUtil.d(TAG, "requestFailure");
                sendMsgRecord.msg_send_status = MessageEntity.MsgSendStatus.FAILED.toNumber();
                messageList.justRefresh();
                MessageRecordDao.getInstance().updateMessageEntityStatus(sendMsg.msg_sender_id, MessageEntity
                .MsgSendStatus.FAILED.toNumber());

                subscription = ChatRecordDao.getInstance().getIChatRecordOperation()
                        .updateMsgRecordSendStatus(sendMsgRecord.inserttime, MessageEntity.MsgSendStatus.FAILED
                        .toNumber())
                        .subscribeOn(Schedulers.io())
                        .subscribe(commonAction);
//                ChatRecordDao.getInstance().updateMsgRecordSendStatus(sendMsgRecord.inserttime, MessageEntity
.MsgSendStatus.FAILED.toNumber());
            }

            @Override
            public void requestSuccess(BaseReturnBean result) throws Exception {
                LogUtil.d(TAG, "requestSuccess >>>" + result.toString());
                if (ErrorCode.SUCCESS_CODE_WNX.equals(result.code)) {
                    //code == 030000
                    sendMsgRecord.msg_send_status = MessageEntity.MsgSendStatus.SUCCESS.toNumber();
                    JSONObject jsonObject = new JSONObject(result.data);
                    String msg_id = jsonObject.optString("msg_id");
                    sendMsgRecord.msg_id = msg_id;
                    //保存状态和消息id
                    subscription = ChatRecordDao.getInstance().getIChatRecordOperation()
                            .updateMsgRecordMsgId(sendMsgRecord.inserttime, msg_id)
                            .subscribeOn(Schedulers.io())
                            .subscribe(commonAction);
//                    ChatRecordDao.getInstance().updateMsgRecordMsgId(sendMsgRecord.inserttime, msg_id);
                    //更新成功状态
                    subscription = ChatRecordDao.getInstance().getIChatRecordOperation()
                            .updateMsgRecordSendStatus(sendMsgRecord.inserttime, sendMsgRecord.msg_send_status)
                            .subscribeOn(Schedulers.io())
                            .subscribe(commonAction);
//                    ChatRecordDao.getInstance().updateMsgRecordSendStatus(sendMsgRecord.inserttime, sendMsgRecord
.msg_send_status);
                } else {
                    //失败
                    sendMsgRecord.msg_send_status = MessageEntity.MsgSendStatus.FAILED.toNumber();
                    //更新失败状态
                    ChatRecordDao.getInstance().getIChatRecordOperation()
                            .updateMsgRecordSendStatus(sendMsgRecord.inserttime, sendMsgRecord.msg_send_status)
                            .subscribeOn(Schedulers.io())
                            .subscribe(commonAction);
//                    ChatRecordDao.getInstance().updateMsgRecordSendStatus(sendMsgRecord.inserttime, sendMsgRecord
.msg_send_status);
                }
                //刷新列表
                messageList.justRefresh();
                //更新消息列表，的发送状态
                MessageRecordDao.getInstance().updateMessageEntityStatus(sendMsg.msg_sender_id, sendMsgRecord
                .msg_send_status);
//
            }

            @Override
            public void requestSuccess(String result) throws Exception {

            }
        });
    }*/

//    /**
//     * 构建发送的map
//     */
//    protected void buildSendMap() {
//        LogUtil.d(TAG, "buildSendMap");
//
//        sendMap.put("user_id", userId);
//        LogUtil.d(TAG, "buildSendMap userId >>" + userId);
//        sendMap.put("msg_type", message.msg_content_type);
//        LogUtil.d(TAG, "buildSendMap msg_content_type >>" + message.msg_content_type);
//        if (message.msg_type == MessageEntity.MsgType.CHAT_SINGLE.toNumber()) {
//            sendMap.put("msg_recevier_id", message.msg_sender_id);
//            LogUtil.d(TAG, "buildSendMap msg_recevier_id >>" + userId);
//        } else if (message.msg_type == MessageEntity.MsgType.CHAT_CROUP.toNumber()) {
//            sendMap.put("msg_recevier_id", message.msg_group_id);
//            LogUtil.d(TAG, "buildSendMap msg_recevier_id >>" + userId);
//        }
//        sendMap.put("msg_text", message.msg_content);
//    }
    private void requestNetWork() {
        if (mDataList.size() > 0 && !TextUtils.isEmpty(mDataList.get(0).msg_id)) {
            mPageBean.page_index = mDataList.get(0).msg_id;
        }
        if (mDataList.size() == 0) {
            mPageBean.page_turn = PageUtil.PAGE_DOWN;
        } else {
            mPageBean.page_turn = PageUtil.PAGE_UP;
        }
        dataMap.put("pg", mPageBean);
        String url = "";

        if (isSingleChat()) {
            url = Constants.queryHXSingleChatMsg;
        } else {
            url = Constants.QUERY_MULTI_CHATRECORD;
        }

        //服务器数据
        OkHttpManager.getInstance().commonRequest(url, dataMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<MsgRecordEntity>>() {
                    @Override
                    public List<MsgRecordEntity> call(BaseReturnBean baseReturnBean) {

                        List<MsgRecordEntity> msgList = new ArrayList<MsgRecordEntity>();
                        try {
                            JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject json = jsonArray.getJSONObject(i);
                                MsgRecordEntity entity = new MsgRecordEntity();
                                if (isSingleChat()) {
                                    entity.msg_type = MsgType.CHAT_SINGLE.toNumber();
                                    entity.msg_sender_id = otherId;
                                } else {
                                    entity.msg_type = MsgType.CHAT_CROUP.toNumber();
                                    entity.msg_group_id = otherId;
                                    entity.msg_group_name = name;
                                }
                                String senderId = json.optString("user_id");
                                if (userId.equals(senderId)) {
                                    entity.is_mine = "1";
                                }
                                entity.msg_sender_name = json.optString("user_name");
                                entity.msg_logo = json.optString("user_logo");
                                entity.msg_id = json.optString("msg_id");
                                entity.msg_sender_id = senderId;

                                entity.msg_content_type = json.optInt("msg_type");
                                entity.msg_content = ChatFileEntity.getContentByType(json.optString("msg_text"),
                                        entity.msg_content_type);
                                if (ChatFileEntity.isNeedSaveFile(entity.msg_content_type)) {
                                    entity.mFileEntity.file_url_remote = json.optString("msg_text");
                                    entity.mFileEntity.file_name = json.optString("msg_name");
                                    entity.mFileEntity.lat = json.optString("msg_lat");
                                    entity.mFileEntity.address_desc = json.optString("msg_postion");
                                    entity.mFileEntity.lng = json.optString("msg_lng");
                                    entity.mFileEntity.msg_dutime = json.optInt("msg_dutime");
                                } else {
                                    entity.msg_content = json.optString("msg_text");
                                }
                                entity.msg_last_time = json.optString("msg_ctime");
                                msgList.add(entity);
//                                entity.msg_last_time = json.optString("msg_ctime");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return msgList;
                    }
                })
                .doOnNext(new Action1<List<MsgRecordEntity>>() {
                    @Override
                    public void call(List<MsgRecordEntity> msgRecordEntities) {
//                        if (!isJustRecord) //如果是查看聊天记录的话,就不再插入数据库
//                        for (MsgRecordEntity entity : msgRecordEntities) {
//                            WNXDBManager.getInstance().insertMsgRecord(entity);
//                        }
                        Collections.reverse(msgRecordEntities);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<MsgRecordEntity>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<MsgRecordEntity> msgRecordEntities) {

                        if (msgRecordEntities.size() < PageUtil.PAGE_SIZE) {
                            haveMoreDataRemote = false;
                        }
                        if (msgRecordEntities.size() == 0) {
                            return;
                        }

                        int oldPostion = msgRecordEntities.size();
                        mDataList.addAll(0, msgRecordEntities);
                        messageList.refreshSeekTo(oldPostion - 1);
                    }
                });
    }

//    Subscriber<List<MsgRecordEntity>> getDataSubRemote =;


    private void setSwipeRefreshListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && (haveMoreDataLocal ||
                                haveMoreDataRemote)) {
                            PAGE_INDEX++;

                            if (haveMoreDataLocal) {
                                //本地数据请求
                                registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                                        .getChatRecordList(id, chatType, PAGE_INDEX, "")
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Subscriber<List<MsgRecordEntity>>() {
                                            @Override
                                            public void onCompleted() {

                                            }

                                            @Override
                                            public void onError(Throwable e) {

                                            }

                                            @Override
                                            public void onNext(List<MsgRecordEntity> msgRecordEntities) {
                                                if (msgRecordEntities.size() < PageUtil.PAGE_SIZE) {
                                                    haveMoreDataLocal = false;
                                                }
                                                int oldPostion = msgRecordEntities.size();
                                                mDataList.addAll(0, msgRecordEntities);
                                                messageList.refreshSeekTo(oldPostion - 1);

                                            }
                                        }));

                            } else {
                                //不走服务器
                                if (haveMoreDataRemote) {
                                    requestNetWork();
                                }
                            }
                            isloading = false;
                        } else {
                            Toast.makeText(getActivity(), getResources().getString(R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

    /**
     * 判断是否可以撤回消息
     *
     * @param mEntity
     * @return
     */
    private boolean isCanWithDrawMessage(MsgRecordEntity mEntity) {
        if (isJustRecord)
            return false;
        //            Date sendDate = DateUtils.stringToDate(mEntity.msg_last_time, null);
//            long sendTime = sendDate.getTime();
        Date curDate = new Date();
        long cerTime = curDate.getTime();
//            long distence = cerTime - sendTime;
        long sendTime = 0L;
        if (!TextUtils.isEmpty(mEntity.inserttime)) {
            sendTime = Long.parseLong(mEntity.inserttime);
        }
        long distence = cerTime - sendTime; //目前服务器时间和本地时间相差过长,导致无法撤回
        LogUtil.d("sendTime>" + sendTime + " cerTime>" + cerTime + " distence>" + distence + "curDate >" + curDate);
        return "1".equals(mEntity.is_mine) && distence < 2 * 60 * 1000 && !isJustRecord;
    }

    /**
     * 几种文本类型对应几种状态 有哪些操作，撤回只能撤回自己发送的并且发送时间在两分钟之内的
     *
     * @param mEntity
     */
    private void bubbleLongClick(final MsgRecordEntity mEntity) {
        LogUtil.d(mEntity.toString());
        List<String> oprateList = new ArrayList<>();
        if (mEntity.msg_content_type == ContentType.TXT.toNumber()) {
            oprateList.add(getResources().getString(R.string.copy));
//            oprateList.add(getResources().getString(R.string.collect)); TODO 暂时不做,预留接口
            if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                oprateList.add(getResources().getString(R.string.forward));
            }

            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
                if (!isJustRecord)
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }


                if (isCanWithDrawMessage(mEntity)) {
                    if (!isJustRecord)
                        oprateList.add(getResources().getString(R.string.withdraw));
                }

            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    if (!isJustRecord)
                        oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }

            }
        } else if (mEntity.msg_content_type == ContentType.VEDIO.toNumber()) {
            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {

            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {

            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {

            }
        } else if (mEntity.msg_content_type == ContentType.VOICE.toNumber()) {
            if (isJustRecord) {
                return;
            }
//            oprateList.add(getResources().getString(R.string.collect));
            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
                if (isCanWithDrawMessage(mEntity)) {
                    if (!isJustRecord)
                        oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    if (!isJustRecord)
                        oprateList.add(getResources().getString(R.string.withdraw));
                }//cn.xspace/app111c11d8a451436
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    if (!isJustRecord)
                        oprateList.add(getResources().getString(R.string.delete));
                }
            }

        } else if (mEntity.msg_content_type == ContentType.PICTURE.toNumber()) {
//            oprateList.add(getResources().getString(R.string.collect));
            if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                oprateList.add(getResources().getString(R.string.forward));
            }

            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }

                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
            }
        } else if (mEntity.msg_content_type == ContentType.FILE.toNumber()) {
//            oprateList.add(getResources().getString(R.string.collect));
            if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                oprateList.add(getResources().getString(R.string.forward));
            }

            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
            }
        } else if (mEntity.msg_content_type == ContentType.LOCATION.toNumber()) {
//            oprateList.add(getResources().getString(R.string.collect));
            if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                oprateList.add(getResources().getString(R.string.forward));
            }

            if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
                if (isCanWithDrawMessage(mEntity)) {
                    oprateList.add(getResources().getString(R.string.withdraw));
                }
            } else if (mEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                if (!isJustRecord) {
                    if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                        oprateList.add(getResources().getString(R.string.delete));
                    }
                }
            }
        } else if (mEntity.msg_content_type == ContentType.OTHER.toNumber()) {
            if (chatType != MsgType.CHAT_QAC_FORM.toNumber()) {
                oprateList.add(getResources().getString(R.string.forward));
            }
        }
        final String[] arr = (String[]) oprateList.toArray(new String[oprateList.size()]);
        LogUtil.d(arr.toString());

        DialogHelp.getSelectDialog(mContext, arr, new SelectDialog.ISelectItemListener() {
            @Override
            public void selectItemClick(int which) {
                String operateion = arr[which];
                if (operateion.equals(getResources().getString(R.string.copy))) {
                    clipboard.setPrimaryClip(ClipData.newPlainText(null,
                            (mEntity.msg_content)));
                    T.showShort(mContext, R.string.content_copyed);
                } else if (operateion.equals(getResources().getString(R.string.collect))) {
                    LogUtil.d(operateion); // TODO 暂时不需要此功能
                } else if (operateion.equals(getResources().getString(R.string.forward))) {
                    LogUtil.d(operateion);
                    Bundle mBundle = new Bundle();
                    if (mEntity.msg_content_type == ContentType.PICTURE.toNumber()) {
                        mEntity.msg_content = mEntity.mFileEntity.file_url_remote;
                    }
                    mBundle.putSerializable(MsgForwardActivity.FORWARD_ENTITY, mEntity);
                    Navigator.startForwardActivity(mContext, mBundle);
                } else if (operateion.equals(getResources().getString(R.string.delete))) {
                    LogUtil.d(operateion);
                    ChatRecordDao.getInstance().getIChatRecordOperation().deleteOneChatRecordByInserTime(mEntity
                            .inserttime)
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Action1<Integer>() {
                                @Override
                                public void call(Integer integer) {
                                    LogUtil.d("删除结果》》" + integer);
                                    boolean isContain = mDataList.contains(mEntity);
                                    LogUtil.d("是否包含》》" + isContain);
                                    if (isContain) {
                                        mDataList.remove(mEntity);
                                        messageList.refresh();
                                    }
                                }
                            });

                } else if (operateion.equals(getResources().getString(R.string.withdraw))) {
                    if (!isCanWithDrawMessage(mEntity)) {
                        //只能撤回两分钟之内的消息
                        T.showShort(mContext, R.string.only_withdraw_two_minute);
                        return;
                    }

                    if (chatType == MsgType.CHAT_SINGLE.toNumber() || chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("user_id", userId);
                        dataMap.put("msg_recevier_id", otherId);
                        dataMap.put("msg_id", mEntity.msg_id);
                        OkHttpManager.getInstance().commonRequest(Constants.REVOKE_SINGLE_CHAT, dataMap)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<BaseReturnBean>() {
                                    @Override
                                    public void call(BaseReturnBean baseReturnBean) {
                                        if (ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                                            String time = baseReturnBean.desc;
                                            T.showShort(mContext, R.string.withdraw_success);
                                            mEntity.msg_content = String.format(getString(R.string
                                                    .who_withdraw_a_message), getString(R.string.you));
                                            mEntity.msg_content_type = ContentType.SYSTEM_WARN.toNumber();
                                            mEntity.msg_last_time = time;
                                            messageList.refresh();
                                            //修改数据库
                                            ChatRecordDao.getInstance().getIChatRecordOperation()
                                                    .updateChatRecordByTime(mEntity.inserttime, mEntity)
                                                    .subscribeOn(Schedulers.io())
                                                    .subscribe(new Action1<String>() {
                                                        @Override
                                                        public void call(String s) {
                                                            LogUtil.d("修改聊天记录表成功");
                                                        }
                                                    });
                                            MessageEntity mesRecord = new MessageEntity().chatRecord2messageRecord
                                                    (mEntity);
                                            MessageRecordDao.getInstance().getiMessageData().updateMessageList
                                                    (mesRecord)
                                                    .subscribeOn(Schedulers.io())
                                                    .subscribe(new Action1<String>() {
                                                        @Override
                                                        public void call(String s) {
                                                            LogUtil.d("修改消息记录表成功");
                                                        }
                                                    });

                                        }
                                    }
                                });
                    } else if (chatType == MsgType.CHAT_CROUP.toNumber()) {
                        Map<String, Object> dataMap = new HashMap<String, Object>();
                        dataMap.put("user_id", userId);
                        dataMap.put("group_id", otherId);
                        dataMap.put("msg_id", mEntity.msg_id);
                        dataMap.put("msg_org", mGroupType); //群聊撤回加群组类型
                        OkHttpManager.getInstance().commonRequest(Constants.REVOKE_MULTI_CHAT, dataMap)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<BaseReturnBean>() {
                                    @Override
                                    public void call(BaseReturnBean baseReturnBean) {
                                        if (ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                                            String time = baseReturnBean.desc;
                                            T.showShort(mContext, R.string.withdraw_success);
//                                            mEntity.msg_content = String.format(getString(R.string
// .who_withdraw_a_message), getString(R.string.you));
//                                            mEntity.msg_content_type = MessageEntity.ContentType.SYSTEM_WARN
// .toNumber();
//                                            mEntity.msg_last_time = time;
//                                            messageList.refresh();
//                                            //修改数据库
//                                            ChatRecordDao.getInstance().getIChatRecordOperation()
// .updateChatRecordByTime(mEntity.inserttime, mEntity)
//                                                    .subscribeOn(Schedulers.io())
//                                                    .subscribe(new Action1<String>() {
//                                                        @Override
//                                                        public void call(String s) {
//                                                            LogUtil.d("修改聊天记录表成功");
//                                                        }
//                                                    });
//                                            MessageEntity mesRecord = new MessageEntity().chatRecord2messageRecord
// (mEntity);
//                                            MessageRecordDao.getInstance().getiMessageData().updateMessageList
// (mesRecord)
//                                                    .subscribeOn(Schedulers.io())
//                                                    .subscribe(new Action1<String>() {
//                                                        @Override
//                                                        public void call(String s) {
//                                                            LogUtil.d("修改消息记录表成功");
//                                                        }
//                                                    });

                                        }
                                    }
                                });
                    }
                }

            }
        }).show();

//        DialogHelp.getSelectDialog(mContext, arr, new SelectDialog.ISelectItemListener() {
//                    @Override
//                    public void selectItemClick(int position) {
//                        String operateion = arr[position];
//                    }
//                }
//        ).show();

    }

    private boolean isContainRecord(String msgId) {
        for (MsgRecordEntity entity : mDataList) {
            if (!TextUtils.isEmpty(msgId) && entity.msg_id.equals(msgId)) {
                return true;
            }
            return false;
        }
        return false;
    }

    String timeLast = "";

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        if (isJustRecord)
            return;
        super.onEventMainThread(inParam);
        LogUtil.d(inParam.toString());
        String type = inParam.get(EventBusConstant.TYPE).toString();
        if (type == null) {
            return;
        }
        if (inParam.get(EventBusConstant.TIME_PUSH_BEAN) != null) {
            String timeNow = inParam.get(EventBusConstant.TIME_PUSH_BEAN).toString();
            LogUtil.d("timeNow " + timeNow);
            if (!TextUtils.isEmpty(timeNow)) {
                if (timeNow.equals(timeLast)) {
                    LogUtil.d("本条消息已经发送过不需再发送了...");
                    return;
                } else {
                    LogUtil.d("本条消息未发送，需要填充UI...");
                }
            }
            timeLast = timeNow;
        }

        if (EventBusConstant.HUANXIN_PUSH.equals(type)) {
            Object bean = inParam.get(EventBusConstant.HUANXIN_PUSH_BEAN);

            if (bean instanceof MsgRecordEntity) {
                LogUtil.d("更新聊天列表");
                LogUtil.d("otherId》》" + otherId);

                MsgRecordEntity pushBean = (MsgRecordEntity) bean;
                LogUtil.d("推送msg_id>>>" + pushBean.msg_id);
                //同一个msg_id，则不需更新
                if (isContainRecord(pushBean.msg_id)) {
                    LogUtil.d("聊天记录存在，不需更新");
                    return;
                } else {
                    LogUtil.d("聊天记录不存在，需更新");
                }

                if (pushBean.msg_type != chatType) {
                    LogUtil.d("chatType 补符合");
                    return;
                }

                if (pushBean.msg_type == MsgType.CHAT_SINGLE.toNumber() && (!otherId.equals(pushBean.msg_sender_id))) {
                    LogUtil.d("senderid 不符合");
                    return;
                }
                if (pushBean.msg_type == MsgType.CHAT_QAC_FORM.toNumber()) {
                    if (!otherId.equals(pushBean.msg_sender_id)) {
                        LogUtil.d("senderid 不符合");
                        return;
                    } else if (formId != null && !formId.equals(pushBean.form_id)) {
                        LogUtil.d("formId 不符合");
                        return;
                    }
                }

                if (pushBean.msg_type == MsgType.CHAT_CROUP.toNumber() && (!otherId.equals(pushBean.msg_group_id))) {
                    LogUtil.d("groupid 不符合");
                    return;
                }
                if (pushBean.msg_content_type == ContentType.SYSTEM_WARN.toNumber() &&
                        pushBean.tip_type == MessageEntity.SystemType.WithDraw.toNumber()) {
                    LogUtil.d("消息撤销");
                    int index = 0;
                    int postion = -1;
                    String insertTime = "";
                    for (MsgRecordEntity entity : mDataList) {
                        if (entity.msg_id.equals(pushBean.msg_id)) {
                            postion = index;
                            insertTime = entity.inserttime;
                        }
                        index++;
                    }
                    mDataList.remove(postion);
                } else if (pushBean.msg_content_type == ContentType.SYSTEM_WARN.toNumber() && pushBean
                        .tip_type == MessageEntity.SystemType.GroupNameChange.toNumber()) {
                    String newName = pushBean.msg_group_name;
                    LogUtil.d(newName);
                    setGroupName(newName, pushBean.group_member);
                } else if (pushBean.msg_content_type == ContentType.SYSTEM_WARN.toNumber() && pushBean
                        .tip_type == MessageEntity.SystemType.Invite.toNumber()) {
                    if (inputMenu.getVisibility() == View.GONE) {
                        inputMenu.setVisibility(View.VISIBLE);
                    }
                }
                mDataList.add(pushBean);
                messageList.refreshSeekTo(listView.getFirstVisiblePosition());
            } else if (bean instanceof String) { //相关操作的字符串
                String operation = (String) bean;
                if (EventBusConstant.SHIFT_OUT_GROUP.equals(operation)) { //踢出
                    isQuit = 1;//某人设置为被踢出状态
                    inputMenu.setVisibility(View.GONE);
                }
            } else if (bean instanceof MessageEntity) {
                mGroupType = ((MessageEntity) bean).group_type;
            } else {
                LogUtil.d("不用更新聊天列表");
            }
        } else if (TAG.equals(inParam.get(EventBusConstant.TYPE))) {
            if (ChatInfoActivity.GROUP_NAME_CHANGE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                mTitleBar.setTitle((String) inParam.get(EventBusConstant.ACTION_VALUE));
            } else if (ChatInfoActivity.GROUP_DELETE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                //群组退出或者删除会话
                if (otherId.equals(inParam.get(EventBusConstant.ACTION_VALUE))) {
                    LogUtil.d("exit ");
                    //退出对应的群组
                    exitActivity2();
                }
            } else if (ChatInfoActivity.CHAT_RECORD.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                String keyId = (String) inParam.get(EventBusConstant.ACTION_VALUE);
                if (ChatActivity.chatActivity.keyId.equals(keyId)) {
                    mDataList.clear();
                    messageList.refresh();
                }
            } else if (ChatInfoActivity.GROUP_MEMBER_DELETE.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                LogUtil.d("删除成员后 更改数量");
                //删除一个
                groupMember -= 1;
                if (groupMember > 0) {
                    mTitleBar.setTxtNumberText(String.format(getResources().getString(R.string.group_number_show),
                            groupMember));
                }
            }
        } else if ("FileActivity".equals(type)) {
            ChooseFileInfo chooseInfo = (ChooseFileInfo) inParam.get("chooseInfo");
            System.out.println("----------------------------:" + chooseInfo.getFileList().size());
            fileSend(chooseInfo);
        } else if (EventBusConstant.ChatFinish.equals(type)) {
            exitActivity2();
        } else if (EventBusConstant.DELETE_FRIEND_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            if (EventBusConstant.DELETE_FRIEND_FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                if (otherId.equals(inParam.get(EventBusConstant.ACTION_VALUE))) {
                    //好友关系解除,关闭聊天界面
                    exitActivity2();
                }
            }
        }
    }

    public int getScrollY() {
        View c = listView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }

    private void registerExtendMenuItem() {
        String[] itemStrings = getActivity().getResources().getStringArray(R.array.attach_chat);
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
        if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
            inputMenu.registerExtendMenuItem("视频通话", R.drawable.selector_video_call, ITEM_VIDEO_CALL,
                    extendMenuItemClickListener);
        }
    }


    //    private Map<String, Object> buildSendMsgMap(MsgRecordEntity message) {
    //单聊
//        sendMap = new HashMap<>();
//        sendMap.put("user_id", userId);
//        sendMap.put("msg_recevier_id", otherId);
//        sendMap.put("msg_type", mContentType);
//        if (ChatFileEntity.isNeedSaveFile(mContentType)) {
//            sendMap.put()
//        }
//        return sendMap;
//    }

    private void getGroupInfo() {
        Map<String, Object> groupMap = new HashMap<>();
        groupMap.put(RequestConstant.KEY_USER_ID, userId);
        groupMap.put(RequestConstant.KEY_GROUP_ID, otherId);
        String url;
        if (mGroupType == Type.GroupType.PROFESSIONAL) {
            url = Constants.QUERY_PRO_GROUP_INFOR;
        } else {
            url = Constants.QUERY_GROUP_INFOR;
        }
        OkHttpManager.getInstance().commonRequest(url, groupMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, GroupEntity>() {
                    @Override
                    public GroupEntity call(BaseReturnBean baseReturnBean) {
                        JSONObject dataJson = null;
                        mGroupEntity = new GroupEntity();
                        StringBuffer nameSb = new StringBuffer();
                        try {
                            dataJson = new JSONObject(baseReturnBean.data);
                            mGroupEntity.group_name = dataJson.optString("group_name");
                            mGroupEntity.group_orgid = dataJson.optString("group_orgid");
                            mGroupEntity.group_orgname = dataJson.optString("group_orgname");
                            mGroupEntity.group_desc = dataJson.optString("group_desc");
                            mGroupEntity.group_owner_id = dataJson.optString("user_id");
                            mGroupEntity.group_owner_name = dataJson.optString("user_name");
                            mGroupEntity.hx_groupid = dataJson.optString("hx_groupid");
                            mGroupEntity.group_members = dataJson.optInt("group_members");
                            mGroupEntity.group_logo = dataJson.optString("group_logo");
                            mGroupEntity.group_type = dataJson.optInt("group_type");
                            isQuit = dataJson.optInt("isquit");
                            JSONArray jsonArray = dataJson.optJSONArray("userList");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.optJSONObject(i);
                                nameSb.append(jsonObject.optString("user_name") + "、");
                            }
                            if (nameSb.lastIndexOf("、") != -1) {
                                nameSb.deleteCharAt(nameSb.lastIndexOf("、"));
                            }
                            groupNameSplit = nameSb.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return mGroupEntity;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GroupEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        T.showShort(mContext, e.getMessage());
                        //获取本地数据
                        MessageRecordDao.getInstance().getiMessageData().getMessageEntityByKeyId(otherId,
                                MsgType
                                        .CHAT_CROUP.toNumber())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<MessageEntity>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(MessageEntity messageEntity) {
                                        if (messageEntity != null) {
                                            setGroupName(messageEntity.msg_group_name, messageEntity.group_member);
                                        }

                                    }
                                });


                    }

                    @Override
                    public void onNext(GroupEntity groupEntity) {
                        name = groupEntity.group_name;
                        logo = groupEntity.group_logo;
                        setGroupName(groupEntity.group_name, groupEntity.group_members);
                        if (isQuit == 1) {
                            T.showSingleL("你已被移出群组");
                            inputMenu.setVisibility(View.GONE);
                        }
                    }
                });
    }

//    Subscriber<MessageEntity> groupInfoLocal =

//    Subscriber<GroupEntity> groupSub =;

    private void setGroupName(String name, int number) {
        if (isJustRecord) {
            mTitleBar.setTitle(getResources().getString(R.string.txt_look_chat_record));
        } else {
            //数量控制
            mTitleBar.setTxtNumberVisible(View.VISIBLE);
            if (number > 0) {
                groupMember = number;
                mTitleBar.setTxtNumberText(String.format(getResources().getString(R.string.group_number_show),
                        number));
            }
            //群组名称显示
            mTitleBar.setTitle(TextUtils.isEmpty(name) ? getResources().getString(R.string.group) : name);

        }
    }

    //判断是否为单聊
    private boolean isSingleChat() {
        if (chatType == MsgType.CHAT_SINGLE.toNumber() || chatType == MsgType.CHAT_QAC_FORM.toNumber()) {
            return true;
        }
        return false;
    }

    /**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!ResourceUtils.isSdcardExist()) {
            Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        String name = EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg";
        LogUtil.d(TAG, "camera name " + name);
        cameraFile = new File(AppConstant.IMAGE_ADDRESS, name);
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                ITEM_TAKE_PICTURE);
    }


    /**
     * 从相册选择图片
     */
    private void selectPicFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, ITEM_PICTURE);
    }

    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(getActivity(), R.string.file_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        //limit the size < 10M
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(getActivity(), R.string.file_is_not_greater_than_10_m, Toast.LENGTH_SHORT).show();
            return;
        }
        sendBase64Msg(file.getAbsolutePath(), mContentType);

//        sendFileMessage(filePath);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d(TAG, "wubaojie>>>onActivityResult: resultCode:" + requestCode);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ITEM_TAKE_PICTURE) { // capture new image
                if (cameraFile != null && cameraFile.exists()) {
                    sendBase64Msg(cameraFile.getAbsolutePath(), ContentType.PICTURE.toNumber());
                }
            } else if (requestCode == ITEM_PICTURE) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
            } else if (requestCode == ITEM_FILE) {
                ChooseFileInfo chooseInfo = (ChooseFileInfo) data.getSerializableExtra("chooseInfo");
                System.out.println("----------------------------:" + chooseInfo.getFileList().size());
                fileSend(chooseInfo);
            } else if (requestCode == ITEM_LOCATION) {
                address = data.getStringExtra(IntentConstant.ADDRESS);
                lat = data.getDoubleExtra(IntentConstant.LATITUDE, 0.0);
                lng = data.getDoubleExtra(IntentConstant.LONGITUDE, 0);
                locaPath = data.getStringExtra(IntentConstant.SNAP_PATH);
                LogUtil.d(TAG, "address " + address + " lat " + lat + " lng " + lng);
                locationSend();
            }
        }
    }

    /**
     * 发送图片
     */
    private void locationSend() {
        mContentType = ContentType.LOCATION.toNumber();
        buildMessageListBean();
        buildMessageRecordBean();
        sendMsgRecord.mFileEntity.file_type = mContentType;
        sendMsgRecord.mFileEntity.file_url_local = locaPath;
        sendMsgRecord.mFileEntity.file_name = new File(locaPath).getName();
        sendMsgRecord.mFileEntity.lat = lat + "";
        sendMsgRecord.mFileEntity.lng = lng + "";
        sendMsgRecord.mFileEntity.address_desc = address;
        updateUIBeforeSend();
    }

    private void fileSend(ChooseFileInfo chooseInfo) {
        for (FileInfo fInfo : chooseInfo.getFileList()) {
            mContentType = ContentType.FILE.toNumber();
            File file = new File(fInfo.getPath());
            if (!file.exists()) {
                Toast.makeText(getActivity(), R.string.file_does_not_exist, Toast.LENGTH_SHORT).show();
                return;
            }
            //limit the size < 10M
            if (file.length() > 10 * 1024 * 1024) {
                Toast.makeText(getActivity(), R.string.file_is_not_greater_than_10_m, Toast.LENGTH_SHORT).show();
                return;
            }
            buildMessageListBean();
            buildMessageRecordBean();
            //保存本地路径
            sendMsgRecord.mFileEntity.file_url_local = file.getAbsolutePath();
            sendMsgRecord.mFileEntity.file_type = mContentType;
            sendMsgRecord.mFileEntity.file_name = file.getName();
            updateUIBeforeSend();
//            sendBase64Msg(file.getAbsolutePath(), mContentType);
        }
    }

    /**
     * 将文件转换为base64发送
     *
     * @param absolutePath
     * @param contentType
     */
    private void sendBase64Msg(String absolutePath, int contentType) {
        LogUtil.d(TAG, "absolutePath " + absolutePath + " contentType" + contentType);
        String fileName = FileUtil.getImageNameByPath(absolutePath);
        if (TextUtils.isEmpty(fileName)) {
            Toast.makeText(mContext, "暂不支持该类文件上传", Toast.LENGTH_SHORT).show();
            return;
        }
        mContentType = contentType;
        buildMessageListBean();
        buildMessageRecordBean();
        //保存本地路径
        sendMsgRecord.mFileEntity.file_url_local = absolutePath;
        sendMsgRecord.mFileEntity.file_name = fileName;
        sendMsgRecord.mFileEntity.file_type = contentType;
        if (mContentType == ContentType.VOICE.toNumber()) {
            sendMsgRecord.mFileEntity.msg_dutime = voiceTime;
        }
        updateUIBeforeSend();
//        new File2Base64Async().execute(sendMsgRecord, new File2Base64Async.FileToBase64Result() {
//            @Override
//            public void requestResult(String reCode, String name, String content) {
//                if (ErrorCode.SUCCESS_CODE_WNX.equals(reCode)) {
//                    sendMsgRecord.msg_content = content;
//                    sendMsgRecord.mFileEntity.file_name = name;
//                    LogUtil.d(TAG, "base 64 转换成功");
//                    updateUIBeforeSend();
//                    //转换成功
//                    //构建map
////                    buildSendMsgMap(content);
////                    sendMap.put("msg_name", name);
////                    sendMsgCallback();
//                }
//            }
//        });
    }

    /**
     * handle the click event for extend menu
     */
    private class MyItemClickListener implements ChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
//            if(chatFragmentHelper != null){
//                if(chatFragmentHelper.onExtendMenuItemClick(itemId, view)){
//                    return;
//                }
//            }
            switch (itemId) {
                case ITEM_PICTURE:
                    LogUtil.d(TAG, "ITEM_PICTURE");
                    mContentType = ContentType.PICTURE.toNumber();
                    selectPicFromLocal();
                    break;
                case ITEM_TAKE_PICTURE:
                    mContentType = ContentType.PICTURE.toNumber();
                    LogUtil.d(TAG, "ITEM_TAKE_PICTURE");
                    selectPicFromCamera();
                    break;
                case ITEM_LOCATION:
                    LogUtil.d(TAG, "ITEM_LOCATION");
                    Intent mIntent = new Intent(mContext, MapLocationGetActivity.class);//打开地图
                    startActivityForResult(mIntent, ITEM_LOCATION);
                    break;
                case ITEM_FILE:
                    mContentType = ContentType.FILE.toNumber();
                    LogUtil.d(TAG, "ITEM_FILE");
                    Intent intentFile = new Intent(mContext, FileActivity.class);
                    startActivityForResult(intentFile, ITEM_FILE);
//                    startActivityForResult(new Intent(getActivity(), EaseBaiduMapActivity.class), REQUEST_CODE_MAP);
                    break;
                case ITEM_VIDEO_CALL:
                    startVideoCall();
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {
        if (!EMClient.getInstance().isConnected())
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        else {
            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", otherId)
                    .putExtra("isComingCall", false));
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

}
